import fs from "fs"
import path from "path"

/**
 * @description: 处理相应后缀文件
 * @param {string} mediaPath 文件路径
 * @param {string} extArr 后缀数组，匹配多种后缀
 * @param {function} callback 处理文件的回调函数 传参是文件路径
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
export async function operateFile(mediaPath: string, extArr: string[], callback: (mediaPath: string) => any){
    let stat = await fs.promises.stat(mediaPath)
    if(stat.isFile()){
        // 文件
        let ext = path.extname(mediaPath).toLowerCase()
        if( extArr.includes( ext ) ){
            await callback(mediaPath)
        }
    }else if( stat.isDirectory() ){
        // 文件夹
        let dir = await fs.readdirSync( mediaPath )
        // 去除文件夹中以.开头的文件
        dir = dir.filter( item => !item.startsWith('.') )
        for( let i of dir ){
            let p = path.resolve( mediaPath, i )
            // 递归
            await operateFile(p, extArr, callback)
        }
    }
}

